<template>
  <v-btn @click="handlePrint" variant="text" :size="size">
      <j-icon size="16" :color="color" >打印机</j-icon>
  </v-btn>
</template>
<script setup lang="ts">
import { withDefaults, defineProps, computed } from "vue";
import printJS from "print-js";
const props = withDefaults(
  defineProps<{
    src: string;
    color?:string;
    size?:string;
  }>(),
  {
    color:'#fff',
    size:'x-small'
  }
);

const printType = computed(() => props.src.endsWith('.pdf') ? 'pdf' : 'image' )

const handlePrint = () => {
  console.log(props.src,printType.value)  
  // if(printType.value === 'pdf') {
  //   debugPrintPDF(props.src)
  // }
  printJS({
    printable: props.src,
    type: printType.value,
    documentTitle: '打印文档',
    onError: function(error) {
        console.error('Print.js 错误:', error);
        alert('打印失败: ' + error);
    },
    onPrintDialogClose: function() {
        console.log('打印对话框已关闭');
    }
  })
};

// 调试版本
function debugPrintPDF(pdfPath: string) {
    // 1. 检查文件是否存在
    fetch(pdfPath)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.blob();
        })
        .then(blob => {
          
            const pdfUrl = URL.createObjectURL(blob);
              console.log('PDF文件可以访问，大小:', blob.size, 'bytes','pdfUrl:',pdfUrl);
            // 开始打印
            printJS({
                printable: pdfUrl,
                type: 'pdf'
            });
        })
        .catch(error => {
            console.error('无法访问PDF文件:', error);
            alert('无法加载PDF文件: ' + error.message);
        });
}


// 原生打印方法
function printPDFNative(pdfUrl: string) {
    // 创建新的窗口打开PDF
    const printWindow = window.open(pdfUrl);
    
    // 等待加载完成后打印
    if(printWindow) {
      printWindow!.onload = function() {
          printWindow?.print();
      };
    }
}
</script>
